<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021/9/11
 * Time: 14:11
 */
namespace app\admin\controller;

use app\BaseController;
use app\index\service\Push;
use app\middleware\AdminCheck;
use Hedeqiang\TenIM\IM;
use Tencent\TLSSigAPIv2;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use Hedeqiang\TenIM\Exceptions\Exception as tenException;
use think\facade\Log;

class User extends BaseController{

    protected $middleware = [
        AdminCheck::class => ['except' 	=> [] ]
    ];



    /**
    *   @SWG\Post(
    *     path="/admin/user/getList",
    *     tags={"后台注册用户相关"},
    *     summary="用户列表",
    *     consumes={"application/json"},
    *     produces={"application/json"},
    *     @SWG\Parameter(
    *      in="query",
    *      required=true,
    *      name="pageNo,pageSize,type,phone",
    *      type="string",
    *      description="pageNo（第一页）,pageSize（一页多少条数据）,type（类型：enable启用，disable（禁用）），phone（手机号）,create_at（注册时间为数组）,platform(平台来源：wx为微信平台，dy为抖音)"),
    *     @SWG\Response(response="200",description="ok")
    *  )
    */
    /**
     * 获取用户列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(){
        validateParam('pageNo,pageSize','pageNo,pageSize');
        $param=input();
        $where[]=['is_deleted','=',0];
        //已启用
        if($param['type'] == 'enable'){
            $where[]=['status','=',1];
        }
        //已禁用
        if($param['type'] == 'disable'){
            $where[]=['status','=',0];
        }
        //用户账号
        if(isset($param['phone']) && !empty($param['phone'])){
            $where[]=['phone','=',$param['phone']];
        }
        //用户昵称
        if(isset($param['nickname']) && !empty($param['nickname'])){
            $where[]=['nickname','like',"%{$param['nickname']}%"];
        }
        //用户账号
        if(isset($param['id']) && !empty($param['id'])){
            $where[]=['id','=',$param['id']];
        }
        //注册时间
        if(isset($param['create_at']) && !empty($param['create_at']) ){
            $where[]=['create_at','between',$param['create_at']];
        }
        //注册平台搜索
        if(isset($param['platform']) && !empty($param['platform'])){
            $where[]=['platform','=',$param['platform']];
        }

        $total=Db::name('user')
            ->where($where)
            ->count();
        $offset=makeOffset($param['pageNo'],$param['pageSize']);

        $list=Db::name('user')
            ->where($where)
            ->limit($offset,$param['pageSize'])
            ->order('create_at desc')
            ->select();
        return success('用户列表',['total'=>$total,'list'=>$list]);
    }



    /**
    *   @SWG\Post(
    *     path="/admin/user/detail",
    *     tags={"后台注册用户相关"},
    *     summary="用户详细信息",
    *     consumes={"application/json"},
    *     produces={"application/json"},
    *     @SWG\Parameter(
    *      in="query",
    *      required=false,
    *      name="id",
    *      type="string",
    *      description="用户的id"),
    *     @SWG\Parameter(
    *      in="query",
    *      required=false,
    *      name="name",
    *      type="string",
    *      description="用户的姓名"),
    *     @SWG\Response(response="200",description="ok")
    *  )
    */
    /**
     * 用户详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(){
        validateParam('id','id');
        $id=input('id');//用户的id
        $detail=Db::name('user')
            ->where('id','=',$id)
            ->find();
        //获取用户的解锁信息
        $unlock_info = Db::name('user_unlock_region')
            ->where('user_id',$id)
            ->select();
        $detail['unlock_info'] = $unlock_info;
        return success('用户详情',$detail);
    }


    /**
     * 城市列表
     * @return \think\response\Json
     */
    public function cityList(){
        //查询拥有考题的城市有多少
        $sql = "SELECT city_ as city FROM chapter GROUP BY city_";
        $city = Db::query($sql);
        foreach ($city as $k=>$v){
            if($v['city'] === '0'){
                $city[$k]['city'] = '全国';
            }
        }
        return success('城市列表',$city);
    }


    /**
     * 添加用户解锁记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addUnlockInfo(){
        validateParam('user_id,region_name,is_unlock_question,is_unlock_skill','user_id,region_name,is_unlock_question,is_unlock_skill');
        $param = input();
        if($param['region_name'] === '全国'){
            $param['region_name'] = '0';
        }
        //首先判断用户是否已经解锁了
        $info = Db::name('user_unlock_region')
            ->where('user_id',$param['user_id'])
            ->where('region_name',$param['region_name'])
            ->find();
        if(empty($info)){
            //直接新增解锁记录
            $data['user_id'] = $param['user_id'];
            $data['region_name'] = $param['region_name'];
            $data['is_unlock_question'] = $param['is_unlock_question'];
            $data['is_unlock_skill'] = $param['is_unlock_skill'];
            $data['update_at'] = currentTime();
            $data['create_at'] = currentTime();

            Db::name('user_unlock_region')->insert($data);
        }else{
            //更新解锁记录
            $data['is_unlock_question'] = $param['is_unlock_question'];
            $data['is_unlock_skill'] = $param['is_unlock_skill'];
            $data['update_at'] = currentTime();
            Db::name('user_unlock_region')
                ->where('id',$info['id'])
                ->update($data);
        }
        return success('添加解锁记录成功');
    }


    /**
     * 删除解锁信息
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function deleteUnlockInfo(){
        validateParam('id','id');
        Db::name('user_unlock_region')
            ->where('id',input('id'))
            ->delete();
        return success('删除成功');
    }



    /**
    *   @SWG\Post(
    *     path="/admin/user/forbid",
    *     tags={"后台注册用户相关"},
    *     summary="用户启用和禁用操作",
    *     consumes={"application/json"},
    *     produces={"application/json"},
    *     @SWG\Parameter(
    *      in="query",
    *      required=true,
    *      name="id",
    *      type="string",
    *      description="用户的id"),
    *     @SWG\Response(response="200",description="ok")
    *  )
    */
    /**
     * 用户启用和禁用操作
     * @return \think\response\Json
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DbException
     */
    public function forbid(){
        validateParam('id','id');
        $id=input('id');
        //首先判断用户的禁用状态
        $status=Db::name('user')
            ->where('id',$id)
            ->value('status');
        if($status === 1){
            Db::name('user')
                ->where('id',$id)
                ->update(['status'=>0]);
            //Cache::store('redis')->set("user_forbid_{$id}",1);
            return success('禁用成功');
        }else{
            //被禁用状态
            Db::name('user')
                ->where('id',$id)
                ->update(['status'=>1]);
            //Cache::store('redis')->delete("user_forbid_{$id}");
            return success('启用成功');
        }
    }

}